#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys,re,wx
from BeautifulSoup import BeautifulSoup
from urllib import urlopen, urlretrieve
from pickle import load, dump
###INDIR###
indir = os.getenv('HOME') + '/.mpy3/lib/'
######
###OUTDIR###
outdir = os.getenv('HOME') + '/Music/'
######
#lib_path = os.path.abspath(indir)
#sys.path.append(lib_path)
#import mpy3funcs

ID_ABOUT = 101
ID_EXIT = 110

class MainWindow(wx.Frame):
	def __init__(self, parent, id, title):
		wx.Frame.__init__(self,parent,wx.ID_ANY,title,size = (400,300),
		                  style = wx.DEFAULT_FRAME_STYLE | 
		                  wx.NO_FULL_REPAINT_ON_RESIZE)
		panel = wx.Panel(self)
		runbutton = wx.Button(panel, label='Run mpy3', pos=(10,10), size=(120,40))
		self.Bind(wx.EVT_BUTTON, self.grab_songs, runbutton)
		addbutton = wx.Button(panel, label='Add feed', pos=(140,10), size=(120,40))
		self.Bind(wx.EVT_BUTTON, self.add_feed, addbutton)
		rembutton = wx.Button(panel, label='Remove feed', pos=(270,10), size=(120,40))
		self.Bind(wx.EVT_BUTTON, self.rem_feed, rembutton)
		
		currentfeeds = wx.StaticText(parent=panel, pos=(10, 60), label='Current Feeds:')
		currentfeeds.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD))
		self.refresh_feed_display(panel)

		self.CreateStatusBar()
		filemenu = wx.Menu()
		filemenu.Append(ID_ABOUT, '&About', 'Program Information')
		filemenu.AppendSeparator()
		filemenu.Append(ID_EXIT, 'E&xit', 'Terminate the program')
		menubar = wx.MenuBar()
		menubar.Append(filemenu, 'File')
		self.SetMenuBar(menubar)
		
		wx.EVT_MENU(self, ID_ABOUT, self.OnAbout)
		wx.EVT_MENU(self, ID_EXIT, self.OnExit)
		
		
		self.Show(True)
		
	def OnAbout(self, event):
		d = wx.MessageDialog(self, 'A sample editor', 'about sample editor', wx.OK)
		d.ShowModal()
		d.Destroy()
		
	def OnExit(self, event):
		self.Close(True)
		
	def grab_songs(self, event):
		
		prgs = wx.ProgressDialog('Grabbing mp3s...', '                                           ', 
									parent=self, 
									maximum=4)
		count = 0
    
	    ############################# GRAB HREF ################################
	    
		href = load(open(indir + 'href.dat','r'))
	    
		for feed in href:
			prgs.Update(count, 'Grabbing ' + feed)
			outdirtemp = outdir + feed + '/'
			source = urlopen(href[feed]).read()
			files = os.listdir(outdirtemp)
			soup = BeautifulSoup(source)
			urls = soup.findAll('a', href=re.compile('.mp3$'))
			mp3_urls = [l['href'] for l in urls] #not sure what this does...
			
			for url in mp3_urls:
				song = str(url).split('/')[-1:][0].replace(' ','').replace('%20','').strip()
				if song not in files:
					prgs.Update(count, 'Downloading ' + song)
					urlretrieve(url, outdirtemp + song)
			count = count + 1
	        
	    ############################# GRAB RSS #####################################
	    
		rss = load(open(indir + 'rss.dat','r'))
	    
		for feed in rss:
			prgs.Update(count, 'Grabbing ' + feed)
			outdirtemp = outdir + feed + '/'
			source = urlopen(rss[feed]).read()
			files = os.listdir(outdirtemp)
			soup = BeautifulSoup(source)
			items = soup.findAll('item')
			
			for item in items:
				song = str(item.findAll('title')[0])
				song = song.split('<title>')[1].split('</title>')[0].strip()
				song = song.replace(' ','').replace('/','--').replace('%20','') + '.mp3'
				if song not in files:
					songurl = str(item.findAll('media:content')[0]).split('"')[1]
					prgs.Update(count, 'Downloading ' + song)
					urlretrieve(songurl, outdirtemp + song)
			count = count + 1
	    
		prgs.Destroy()
		
	def add_feed(self, event):
		box1 = wx.TextEntryDialog(None, 'Please enter the FULL URL of the feed', 'Add feed', 'http://')
		if box1.ShowModal() == wx.ID_OK:
			url = box1.GetValue().strip()
			box2 = wx.TextEntryDialog(None, 'What is the name of the feed?', 'Feed name', '')
			if box2.ShowModal() == wx.ID_OK:
				feedname = box2.GetValue().strip().replace(' ','_')
				
	def rem_feed(self, event):
		box1 = wx.TextEntryDialog(None, 'Which feed?', 'Remove feed', '')
		box1.ShowModal()
		
	def refresh_feed_display(self, panel):
		href = load(open(indir + 'href.dat','r'))
		rss = load(open(indir + 'rss.dat','r'))
		spc = 0
		for h in href.keys():
			temp=wx.StaticText(parent=panel, pos=(25, 80+spc), label=h)
			spc = spc + 25
		for r in rss.keys():
			temp=wx.StaticText(parent=panel, pos=(25, 80+spc), label=r)
			spc = spc + 25
		
		
		

app = wx.PySimpleApp()
frame = MainWindow(None,-1,'mpy3')
app.MainLoop()
